package cse.luanvan;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import luanvan.bus.BaseBusAdapterInstruction;
import luanvan.bus.BaseGlandBusAdapter;
import luanvan.bus.DrawBusNumber;
import luanvan.bus.JSONParser;
import luanvan.bus.PathBus;
import luanvan.bus.UTMLatLng;
import luanvan.bus.UTMLatLng.UTM;
import luanvan.gps.GPSTracker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.bonuspack.overlays.ItemizedOverlayWithBubble;
import org.osmdroid.bonuspack.overlays.MapEventsOverlay;
import org.osmdroid.bonuspack.overlays.MapEventsReceiver;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements MapEventsReceiver,
		LocationListener, SensorEventListener {
	public static MapView map;
	protected GeoPoint startPoint, destinationPoint;
	protected ArrayList<GeoPoint> viaPoints;
	protected static int START_INDEX = -2, DEST_INDEX = -1;
	protected ItemizedOverlayWithBubble<ExtendedOverlayItem> itineraryMarkers,
			serviceMarkers;
	// for departure, destination and viapoints
	protected ExtendedOverlayItem markerStart, markerDestination;
	protected ArrayList<ExtendedOverlayItem> listmarker, listserviceMarker;
	public String StartAddress = "", DestinationAddress = "";
	ArrayList<RoadNode> listRoadNodes;
	ArrayList<String> listInstruction;

	protected Road mRoad;
	protected PathOverlay roadOverlay;

	protected ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodeMarkers;
	private MapEventsOverlay eventTouchOverlay;
	private int ServiceNo;
	MultiAutoCompleteTextView atmAutocomplete;
	GPSTracker gps;
	boolean isBus = false; // true : tim theo xe bus. false: tim duong bo
	String MaxChange = "2";
	private ArrayList<PathBus> dsPathBus = new ArrayList<PathBus>();

	private static final String TAG_RESULT = "Results";
	private static final String TAG_PATHS = "Paths";
	private static final String TAG_TUYEN = "Tuyen";
	private static final String TAG_MATUYEN = "MaTuyen";
	private static final String TAG_TENTUYEN = "TenTuyen";
	private static final String TAG_MATRAM = "MaTram";
	private static final String TAG_TENTRAM = "TenTram";
	private static final String TAG_X = "X";
	private static final String TAG_Y = "Y";
	private static final String TAG_KHOANGCACH = "KhoangCach";
	private static final String TAG_THOIGIAN = "Thoigian";
	private static final String TAG_KMLROUTE = "KMLRoute";
	private static final String TAG_FOUND = "Found";
	private static final String TAG_TRAMDAU = "TramDau";
	private static final String TAG_TRAMCUOI = "TramCuoi";
	private static final int[] BusColors = { Color.parseColor("#4B0082"),
			Color.parseColor("#2E8B57"), Color.parseColor("#660033"),
			Color.parseColor("#000099"), Color.parseColor("#996600"),
			Color.parseColor("#ff00ee") };
	/*
	 * "#222222", "#336600", "#660033", "#000099", "#996600", "#669999",
	 * "#FFCC00", "#ff00ee", "#333", "#444", "#555", "#666", "#777", "#888",
	 * "#999", "#aaa" ,"#ccc"
	 */
	private UTMLatLng utmlatlng;
	AlertDialog.Builder builderBus;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// DisplayMetrics displaymetrics = new DisplayMetrics();
		// getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		// int height = displaymetrics.heightPixels;
		// int width = displaymetrics.widthPixels;
		utmlatlng = new UTMLatLng();// khoi tao class convert utm va latlong

		map = (MapView) findViewById(R.id.map);
		map.setBuiltInZoomControls(true);
		map.setTileSource(TileSourceFactory.MAPNIK);
		MapController myMapcontroller = map.getController();
		myMapcontroller.setZoom(15);

		gps = new GPSTracker(MainActivity.this);
		if (gps.canGetLocation && gps.latitude != 0 && gps.longitude != 0) {
			myMapcontroller
					.setCenter(new GeoPoint(gps.latitude, gps.longitude));
		} else {
			myMapcontroller.setCenter(new GeoPoint(10.78, 106.69));
		}
		// myMapcontroller.setCenter(new GeoPoint(10.78, 106.69));

		// for draw road after route
		roadOverlay = new PathOverlay(Color.BLUE, this);
		Paint painPath = new Paint();
		painPath.setColor(Color.BLUE);
		painPath.setStrokeWidth(8);
		painPath.setAlpha(200);
		painPath.setStyle(Style.STROKE);
		roadOverlay.setPaint(painPath);

		viaPoints = new ArrayList<GeoPoint>();
		// restore departure and destination point
		listserviceMarker = new ArrayList<ExtendedOverlayItem>();
		listmarker = new ArrayList<ExtendedOverlayItem>();
		itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(
				this, listmarker, map);
		serviceMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(
				this, listserviceMarker, map);
		map.getOverlays().add(itineraryMarkers);
		map.getOverlays().add(serviceMarkers);

		MultiAutoCompleteTextView departure = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete_departure);
		MultiAutoCompleteTextView destination = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete_destination);
		atmAutocomplete = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete_atm);

		String[] itemsAtms = getResources().getStringArray(R.array.atm);
		ArrayAdapter<String> AtmAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, itemsAtms);
		atmAutocomplete
				.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
		atmAutocomplete.setAdapter(AtmAdapter);
		atmAutocomplete.setThreshold(2);

		departure.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
		destination
				.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
		String[] roads = getResources().getStringArray(R.array.roads);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, roads);

		departure.setAdapter(adapter);
		departure.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				StartAddress = (String) adapterview.getItemAtPosition(position);

			}
		});
		destination.setAdapter(adapter);
		destination.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				DestinationAddress = (String) adapterview
						.getItemAtPosition(position);

			}
		});

		View btnIntruction = findViewById(R.id.buttonInstruction);
		btnIntruction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isBus)
					ShowBusInstruction();
				else
					ShowInstruction();
			}
		});
		View btnExpander = findViewById(R.id.expander);
		btnExpander.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				View findpanel = findViewById(R.id.search_panel);
				if (findpanel.getVisibility() == View.VISIBLE)
					findpanel.setVisibility(View.GONE);
				else
					findpanel.setVisibility(View.VISIBLE);
			}
		});
		Button btnfinddep = (Button) findViewById(R.id.buttonSearchDep);
		btnfinddep.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startPoint = null;
				if (StartAddress == "") {
					MultiAutoCompleteTextView depCom = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete_departure);
					StartAddress = depCom.getText().toString();
				}
				if (StartAddress != "") {
					AddOverlayDefault();// xoa overlay
					// ve lai marker des
					if (destinationPoint != null) {

						markerDestination = putMarkerItem(markerDestination,
								destinationPoint, DEST_INDEX,
								R.string.destination,
								R.drawable.marker_destination, -1);
					}
					new ExecuteLocation().execute(new String[] { "-2",
							StartAddress });
					// WebService sv = new WebService(StartAddress);
					// String kq = sv.getLatLong();
					// handleButtonSearchLocation(START_INDEX, kq);
				}
			}
		});
		Button btnfindDes = (Button) findViewById(R.id.buttonSearchDest);
		btnfindDes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				destinationPoint = null;
				if (DestinationAddress == "") {
					MultiAutoCompleteTextView desCom = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete_destination);
					DestinationAddress = desCom.getText().toString();
				}
				if (DestinationAddress != "") {
					AddOverlayDefault();
					if (startPoint != null) {

						markerStart = putMarkerItem(markerStart, startPoint,
								START_INDEX, R.string.departure,
								R.drawable.marker_departure, -1);
					}
					new ExecuteLocation().execute(new String[] { "-1",
							DestinationAddress });
					// WebService sv = new WebService(DestinationAddress);
					// String kq = sv.getLatLong();
					// handleButtonSearchLocation(DEST_INDEX, kq);
				}
				// handleButtonSearchLocation(DEST_INDEX, R.id.editDestination);
			}
		});

		MapEventsReceiver mReceiver = new MapEventsReceiver() {

			@Override
			public boolean singleTapUpHelper(IGeoPoint p) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean longPressHelper(final IGeoPoint p) {
				// TODO Auto-generated method stub
				Point po = new Point();
				
				map.getProjection().toMapPixels(p, po);

				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);
				builder.setTitle("Chọn địa điểm");
				builder.setMessage("Bạn muốn chọn vị trí này là...");
				builder.setPositiveButton("Điểm đầu",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								handleTouch((GeoPoint) p, START_INDEX);
							}
						});
				builder.setNegativeButton("Bỏ qua",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						});
				builder.setNeutralButton("Đích đến",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								handleTouch((GeoPoint) p, DEST_INDEX);
							}
						});

				builder.show();
				return false;
			}

			@Override
			public boolean doubleTapUpHelper(int zoomlevel) {

				return false;
			}

		};
		eventTouchOverlay = new MapEventsOverlay(getApplicationContext(),
				mReceiver);
		map.getOverlays().add(eventTouchOverlay);
		map.invalidate();

	}

	public class ExecuteLocation extends AsyncTask<String, Void, Void> {
		String kq;
		int index;

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			index = Integer.parseInt(params[0]);
			WebService sv = new WebService(params[1]);
			kq = sv.getLatLong();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			handleButtonSearchLocation(index, kq);
			super.onPostExecute(result);
		}
	}

	public void SearchClick(View view) {
		if (startPoint != null && destinationPoint != null) {
			Toast.makeText(MainActivity.this, "Loading...", Toast.LENGTH_SHORT)
					.show();
			if (isBus)
				// DrawPathBus(); // tim theo xe bus
				new ExecuteRouteBus().execute();
			else
				// route(); // tim duong di
				new ExecuteRouteRoad().execute();
			return;
		}

	}
	public void ServiceATM(){
		double latservice, longservice;
		if (startPoint != null) {
			
			latservice = startPoint.getLatitudeE6() / 1E6;
			longservice = startPoint.getLongitudeE6() / 1E6;
		} else {
			if (gps.location != null && gps.latitude != 0
					&& gps.longitude != 0) {
				latservice = gps.latitude;
				longservice = gps.longitude;
			} else {
				Toast.makeText(getBaseContext(), "Bạn chưa chọn vị trí",
						Toast.LENGTH_LONG).show();
				return;
			}
		}
		try{
		new ExecuteServiceAtm().execute(new Double[]{latservice,longservice});
		}catch(Exception ex){}
	}

	public class ExecuteServiceAtm extends AsyncTask<Double, Void, Void> {
		String kq;
		double latservice, longservice;

		@Override
		protected Void doInBackground(Double... params) {
			// TODO Auto-generated method stub
			latservice = params[0];
			longservice = params[1];
			WebService sv = new WebService(latservice, longservice, 2,
					ServiceNo, atmAutocomplete.getText().toString()
							.replace(",", ""));
			kq = sv.getService();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (kq == null) {
				Toast.makeText(
						getBaseContext(),
						"Không tìm thấy kết quả\nVui lòng kiểm tra lại kết nối mạng\nhoặc chọn vị trí khác",
						Toast.LENGTH_LONG).show();
				return;
			}
			String[] dsServices = kq.split(";");
			serviceMarkers.removeAllItems();
			if (!kq.contains("Connection refused")) {
				for (String str : dsServices) {
					String[] details = str.split("_");
					GeoPoint p = new GeoPoint(Double.parseDouble(details[2]),
							Double.parseDouble(details[3]));
					// serviceOverlay.addItem(p, details[0],details[1]);
					Drawable marker = getResources()
							.getDrawable(R.drawable.atm);
					String title = details[0] + "\n" + details[1];
					ExtendedOverlayItem overlayItem = new ExtendedOverlayItem(
							title, "", p, getBaseContext());
					overlayItem
							.setMarkerHotspot(OverlayItem.HotspotPlace.BOTTOM_CENTER);
					overlayItem.setMarker(marker);
					serviceMarkers.addItem(overlayItem);
				}
			} else {
				Toast.makeText(MainActivity.this, kq, Toast.LENGTH_LONG).show();
			}
			map.getController()
					.setCenter(new GeoPoint(latservice, longservice));
			map.invalidate();
			super.onPostExecute(result);
		}

	}

	public void ClickButtonSearchAtm(View view) {
		ServiceATM();
	}
	public void ServiceCafeKake(Integer type){
		double latservice, longservice;
		if (startPoint != null) {
			latservice = startPoint.getLatitudeE6() / 1E6;
			longservice = startPoint.getLongitudeE6() / 1E6;
			
		} else {
			if (gps.location != null && gps.latitude != 0
					&& gps.longitude != 0) {
				latservice = gps.latitude;
				longservice = gps.longitude;
			} else {
				Toast.makeText(MainActivity.this, "Bạn chưa chọn vị trí",
						Toast.LENGTH_LONG).show();
				return;
			}
		}
		new ExecuteServiceEntertain().execute(new String[] {type.toString(),String.valueOf(latservice),String.valueOf(longservice)});
	}
	public class ExecuteServiceEntertain extends AsyncTask<String, Void, Void> {
		String kq;
		double latservice, longservice;
		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			int serviceType =Integer.parseInt(params[0]);
			latservice =Double.parseDouble(params[1]);
			longservice =Double.parseDouble(params[2]);

			WebService service = new WebService();
			kq = service.getServiceEntertain(latservice, longservice,
					serviceType);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (kq == null) {
				Toast.makeText(
						getBaseContext(),
						"Không tìm thấy kết quả\nVui lòng kiểm tra lại kết nối mạng\nhoặc chọn vị trí khác",
						Toast.LENGTH_LONG).show();
				return;
			}
			map.getController().setCenter(new GeoPoint(latservice, longservice));
			String[] dsServices = kq.split(";");
			serviceMarkers.removeAllItems();
			if (!kq.contains("Connection refused")) {
				for (String str : dsServices) {
					String[] details = str.split("_");
					GeoPoint p = new GeoPoint(Double.parseDouble(details[3]),
							Double.parseDouble(details[4]));
					// serviceOverlay.addItem(p, details[0],details[1]);
					Drawable marker;
					if (ServiceNo == 167)
						marker = getResources().getDrawable(
								R.drawable.music_live_blue);
					else
						marker = getResources().getDrawable(
								R.drawable.marker_poi); 
					String title = details[0]
							+ "\n"
							+ details[1]
							+ "\n"
							+ "Khoảng cách: "
							+ String.format("%.3f",
									Double.parseDouble(details[2])) + " km";
					ExtendedOverlayItem overlayItem = new ExtendedOverlayItem(
							title, "", p, getBaseContext());
					overlayItem
							.setMarkerHotspot(OverlayItem.HotspotPlace.BOTTOM_CENTER);
					overlayItem.setMarker(marker);
					serviceMarkers.addItem(overlayItem);
				}
			} else {
				Toast.makeText(getBaseContext(), kq, Toast.LENGTH_LONG).show();
			}
			map.getController().setZoom(16);
			map.invalidate();
			super.onPostExecute(result);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		MenuInflater inflat = getMenuInflater();
		inflat.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		View searchpanel = findViewById(R.id.search_panel);
		View layoutdeparture = findViewById(R.id.layoutdeparture);
		View layoutdestination = findViewById(R.id.layoutdestiantion);
		View vieatm = findViewById(R.id.layoutatm);
		switch (item.getItemId()) {
		case R.id.atmmenu:
			ServiceNo = 4; // phan muc cha = 4 atm
			vieatm.setVisibility(View.VISIBLE);
			layoutdestination.setVisibility(View.GONE);
			layoutdeparture.setVisibility(View.GONE);
			searchpanel.setVisibility(View.VISIBLE);
			RemoveItems();
			break;
		case R.id.findroadmenu:
			isBus = false;
			serviceMarkers.removeAllItems();
			vieatm.setVisibility(View.GONE);
			layoutdestination.setVisibility(View.VISIBLE);
			layoutdeparture.setVisibility(View.VISIBLE);
			searchpanel.setVisibility(View.VISIBLE);
			RemoveItems();
			break;
		case R.id.karaokemenu:
			ServiceNo = 167; // phan muc id = 167
			// ServiceEntertain(ServiceNo);
			RemoveItems();
			searchpanel.setVisibility(View.GONE);
			//new ExecuteServiceEntertain().execute(new Integer[] { 167 });
			ServiceCafeKake(167);
			break;
		case R.id.cafemenu:
			RemoveItems();
			ServiceNo = 41; // phan muc id= 41
			// ServiceEntertain(ServiceNo);
			searchpanel.setVisibility(View.GONE);
			//new ExecuteServiceEntertain().execute(new Integer[] { 41 });
			ServiceCafeKake(41);
			break;
		case R.id.busmenu:
		
			isBus = true;
			serviceMarkers.removeAllItems();
			vieatm.setVisibility(View.GONE);
			layoutdestination.setVisibility(View.VISIBLE);
			layoutdeparture.setVisibility(View.VISIBLE);
			searchpanel.setVisibility(View.VISIBLE);
			RemoveItems();

			break;
		case R.id.listbus:

			if (builderBus == null) {
				String[] glandBus = getResources().getStringArray(
						R.array.glandbus);
				builderBus = new AlertDialog.Builder(this);
				builderBus.setTitle("Danh sách tuyến xe bus");
				builderBus.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							}
						});

				builderBus.setAdapter(new BaseGlandBusAdapter(
						MainActivity.this, glandBus), null);
			}
			builderBus.show();
			break;
		case R.id.settings:
			Intent intent = new Intent(this,settings.class);
			intent.putExtra("MaxChange", MaxChange);
			startActivityForResult(intent, 1);
		}

		// if(ServiceNo==4){
		// listViewService.setVisibility(View.VISIBLE);
		// autoComplete.setVisibility(View.VISIBLE);
		// btnfindService.setVisibility(View.VISIBLE);
		// }
		map.invalidate();
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1){
			if(data!=null){
				String message=data.getStringExtra("MaxChange");
				MaxChange=message;
			}
		}
	}

	// add point when touch on map
	public void handleTouch(GeoPoint p, int index) {
		String latlon = String.valueOf(p.getLatitudeE6() / 1E6) + ","
				+ String.valueOf(p.getLongitudeE6() / 1E6);
		handleButtonSearchLocation(index, latlon);

	}

	public void RemoveItems() {
		TextView info = (TextView) findViewById(R.id.routeInfo);
		info.setText("");
	//	itineraryMarkers.removeAllItems();
		roadOverlay.clearPath();
	//	startPoint = null;
	//	destinationPoint = null;
		map.getOverlays().clear();
		map.getOverlays().add(itineraryMarkers);
		map.getOverlays().add(eventTouchOverlay);
		map.getOverlays().add(serviceMarkers);
	}

	public void AddOverlayDefault() {

		map.getOverlays().clear();
		map.getOverlays().add(itineraryMarkers);
		map.getOverlays().add(eventTouchOverlay);
		map.getOverlays().add(serviceMarkers);

	}

	public Address GetLocation(List<Address> list) {
		if (list.size() == 0)
			return null;
		for (int i = 0; i < list.size(); i++) {
			Address adr = list.get(i);
			if (adr.getLatitude() >= 10.6849 && adr.getLatitude() <= 10.8906
					&& adr.getLongitude() >= 106.5667
					&& adr.getLongitude() <= 106.8050)
				return adr;
		}
		return null;
	}

	public void route() {
		AddOverlayDefault();

		RoadManager roadmanager = new luanvan.routing.MapQuestRoadManager();
		// RoadManager roadmanager=new luanvan.routing.OSRMRoadManager();
		// roadmanager.addRequestOption("route=bicycle");
		roadmanager.addRequestOption("routeType=bicycle");
		ArrayList<GeoPoint> wayspoints = new ArrayList<GeoPoint>();
		wayspoints.add(startPoint);
		wayspoints.add(destinationPoint);
		// wayspoints.add(new GeoPoint(10.767431,106.608406));
		Road roads = roadmanager.getRoad(wayspoints);

		if (listRoadNodes != null) {

			listRoadNodes.clear();
		}

		// luu cac vi tri de ve mui ten
		listRoadNodes = roadmanager.getListRoadNode();

		roadOverlay.clearPath();

		for (int i = 0; i < roads.mNodes.size(); i++) {
			RoadNode node = roads.mNodes.get(i);
			GeoPoint p = new GeoPoint(node.mLocation.getLatitudeE6(),
					node.mLocation.getLongitudeE6());
			roadOverlay.addPoint(p);
		}
		// Add Route Overlays into map
		map.getOverlays().add(roadOverlay);
		int count = 0;
		for (int i = 0; i < listRoadNodes.size() - 1; i++) {
			Overlay ns = new DrawableMapOverlay(this,
					listRoadNodes.get(i).mLocation,
					listRoadNodes.get(i + 1).mLocation);
			count++;
			if (count == 2) {
				map.getOverlays().add(ns);
				count = 0;
			}

		}
		// arrow_overlays.addAll(lstArrow);
		map.invalidate();

		TextView txinfo = (TextView) findViewById(R.id.routeInfo);
		// String km=roads.mLength
		txinfo.setText(String.valueOf("Dài : "
				+ String.format("%.2f", roads.mLength) + " km"));

		listInstruction = roadmanager.getInstruction();
		ShowInstruction();

		// roadOverlay.addPoint(startPoint);
		// roadOverlay.addPoint(destinationPoint);

	}

	public String getURL() {

		UTM utm1 = utmlatlng.LatLngToUTMRef(startPoint.getLongitudeE6() / 1E6,
				startPoint.getLatitudeE6() / 1E6);
		UTM utm2 = utmlatlng.LatLngToUTMRef(
				destinationPoint.getLongitudeE6() / 1E6,
				destinationPoint.getLatitudeE6() / 1E6);

		String url = "http://bando24h.com/Server.aspx?action=FindRouteWithConstraint&FindRange=400&NearStationRange=200&WalkSpeed=5&BusSpeed=30&MaxChange="+MaxChange+"&"
				+ "X1="
				+ String.valueOf(utm1.x)
				+ "&Y1="
				+ String.valueOf(utm1.y)
				+ "&X2="
				+ String.valueOf(utm2.x)
				+ "&Y2=" + String.valueOf(utm2.y) + "";

		;
		return url;
	}

	public void getRoadBus() throws UnsupportedEncodingException {

		dsPathBus.clear();
		JSONArray arrayPath = null;
		// connection.doGet("http://bando24h.com/Server.aspx?action=FindRouteWithConstraint&FindRange=400&NearStationRange=200&WalkSpeed=5&BusSpeed=30&MaxChange=2&X1=684920.60&Y1=1192530.94&X2=680208.62&Y2=1191577.19");
		ArrayList<PathBus> pathBus = new ArrayList<PathBus>();
		JSONParser jsonParser = new JSONParser();

		JSONObject jsonObject = jsonParser.getJSONFromUrl(getURL());

		Log.d("json", jsonParser.sttConnect.toString());

		if (jsonParser.sttConnect.getStatusCode() != 200) {
			Toast.makeText(
					this,
					"Invalid respone from server bando24h "
							+ jsonParser.sttConnect.toString(),
					Toast.LENGTH_LONG).show();
			return;
		}
		try {
			if (jsonObject.getBoolean(TAG_FOUND)) {
				arrayPath = jsonObject.getJSONArray(TAG_RESULT)
						.getJSONObject(0).getJSONArray(TAG_PATHS);
				for (int i = 0; i < arrayPath.length(); i++) {
					JSONObject obj = arrayPath.getJSONObject(i);
					PathBus bus = new PathBus();
					bus.KhoangCach = obj.getDouble(TAG_KHOANGCACH);
					bus.ThoiGian = obj.getDouble(TAG_THOIGIAN);
					bus.KMLRoute = obj.getString(TAG_KMLROUTE);
					JSONObject tuyen = obj.getJSONObject(TAG_TUYEN);
					bus.tuyen.MaTuyen = tuyen.getString(TAG_MATUYEN);
					bus.tuyen.TenTuyen = tuyen.getString(TAG_TENTUYEN);
					JSONObject tramdau = obj.getJSONObject(TAG_TRAMDAU);
					bus.tramDau.MaTram = tramdau.getString(TAG_MATRAM);
					bus.tramDau.TenTram = tramdau.getString(TAG_TENTRAM);
					GeoPoint p = utmlatlng.UTMRefToLatLng(
							tramdau.getDouble(TAG_X), tramdau.getDouble(TAG_Y));
					bus.tramDau.X = p.getLatitudeE6() / 1E6;
					bus.tramDau.Y = p.getLongitudeE6() / 1E6;
					JSONObject tramcuoi = obj.getJSONObject(TAG_TRAMCUOI);
					bus.tramCuoi.MaTram = tramcuoi.getString(TAG_MATRAM);
					bus.tramCuoi.TenTram = tramcuoi.getString(TAG_TENTRAM);
					bus.tramCuoi.X = tramcuoi.getDouble(TAG_X);
					bus.tramCuoi.Y = tramcuoi.getDouble(TAG_Y);

					pathBus.add(bus);
				}
			} else {
				Toast.makeText(this, "Can not found result", Toast.LENGTH_LONG)
						.show();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dsPathBus = pathBus;

	}

	public void DrawPathBus() {
		AddOverlayDefault();
		// try {
		// getRoadBus();
		// } catch (UnsupportedEncodingException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		ArrayList<PathBus> listPathBus = dsPathBus;
		roadOverlay.clearPath();
		int count = 0;
		for (int i = 0; i < listPathBus.size(); i++) {

			PathBus bus = listPathBus.get(i);

			PathOverlay pathbusOverlay = new PathOverlay(BusColors[count],
					MainActivity.this);
			Paint painPath = new Paint();
			painPath.setColor(BusColors[count]);
			painPath.setStrokeWidth(8);
			painPath.setAlpha(200);
			painPath.setStyle(Style.STROKE);
			pathbusOverlay.setPaint(painPath);
			count++; // co 5 mau tat ca
			if (count > 5)
				count = 0;

			// draw bus number

			// draw path bus
			String KMLRoute = bus.KMLRoute;
			String[] kmlRoutes = KMLRoute.split(" ");
			int cach = bus.KhoangCach > 800 ? (int) (kmlRoutes.length * 800 / bus.KhoangCach)
					: 0;
			ArrayList<GeoPoint> listPointToArrow = new ArrayList<GeoPoint>();
			int dem = 0;
			GeoPoint point = null;
			for (int j = 0; j < kmlRoutes.length; j++) {
				try {
					dem++;
					if ((dem == cach - 2 || dem == cach-1) && cach > 0) {
						listPointToArrow.add(point);
						if (dem == cach-1)
							dem = 0;
					}
					double lat = Double.parseDouble(kmlRoutes[j].split(",")[1]);
					double lng = Double.parseDouble(kmlRoutes[j].split(",")[0]);
					point = new GeoPoint(lat, lng);

					pathbusOverlay.addPoint(point);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			map.getOverlays().add(pathbusOverlay);

			for (int k = 0; k < listPointToArrow.size()-1; k += 2) {
				Overlay ar = new DrawableMapOverlay(this,
						listPointToArrow.get(k), listPointToArrow.get(k + 1));
				map.getOverlays().add(ar);
			}

			GeoPoint p = new GeoPoint(bus.tramDau.X, bus.tramDau.Y);
			DrawBusNumber num = new DrawBusNumber(MainActivity.this, p,
					bus.tuyen.MaTuyen);
			map.getOverlays().add(num);
		}

		map.getController().setCenter(startPoint);
		if (listPathBus.size() > 0)
			ShowBusInstruction();
	}

	public void ShowInstruction() {
		if (listInstruction == null) {
			Toast.makeText(this, "Không có kết quả nào!", Toast.LENGTH_LONG)
					.show();
			return;
		}
		String[] items = listInstruction.toArray(new String[listInstruction
				.size()]);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Kết quả tìm kiếm");
		TextView info = (TextView) findViewById(R.id.routeInfo);
		String infoo = info.getText().toString()
				.replace("Dài", "Tổng quãng đường");
		builder.setPositiveButton(infoo, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});

		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		}).show();

	}

	public void ShowBusInstruction() {
		if (dsPathBus == null) {
			Toast.makeText(this, "Không có kết quả nào!", Toast.LENGTH_LONG)
					.show();
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Kết quả tìm kiếm");
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});

		builder.setAdapter(new BaseBusAdapterInstruction(MainActivity.this,
				dsPathBus), null);
		builder.show();

	}

	@SuppressLint("NewApi")
	public void handleButtonSearchLocation(int index, String latlon) {
		// EditText edit = (EditText) findViewById(edittext);
		// String addressLocation = edit.getText().toString();
		if (latlon == null) {
			Toast.makeText(
					getApplicationContext(),
					"Không tìm thấy kết quả\nVui lòng kiểm tra lại kết nối mạng\nhoặc chọn vị trí khác để tìm kiếm",
					Toast.LENGTH_LONG).show();
			return;
		}
		try {
			String[] latlons = latlon.split(",");

			double lat = Double.parseDouble(latlons[0]);
			double lng = Double.parseDouble(latlons[1]);

			/*
			 * List<Address> foundAdress = geoNo.getFromLocationName(
			 * addressLocation, 20, 10.6849, 106.5667, 10.8906, 106.8050);
			 */

			// List<Address> foundAdress = geoNo.getFromLocation(lat, lng, 10);
			// Address address = GetLocation(foundAdress);
			if (index == START_INDEX) {
				// startPoint = new GeoPoint(address.getLatitude(),
				// address.getLongitude());
				startPoint = new GeoPoint(lat, lng);
				markerStart = putMarkerItem(markerStart, startPoint,
						START_INDEX, R.string.departure,
						R.drawable.marker_departure, -1);
				map.getController().setCenter(startPoint);
			} else if (index == DEST_INDEX) {
				// destinationPoint = new GeoPoint(address.getLatitude(),
				// address.getLongitude());
				destinationPoint = new GeoPoint(lat, lng);
				markerDestination = putMarkerItem(markerDestination,
						destinationPoint, DEST_INDEX, R.string.destination,
						R.drawable.marker_destination, -1);
				map.getController().setCenter(destinationPoint);
			}
			// map.getController().setZoom(15);

			// if (startPoint != null && destinationPoint != null)
			// try{
			// if (Build.VERSION.SDK_INT >= 11) {
			// //--post GB use serial executor by default --
			// new
			// ExcuteRoute().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			// } else {
			// //--GB uses ThreadPoolExecutor by default--
			// new ExcuteRoute().execute();
			// }
			// }catch (Exception e) {
			// // TODO: handle exception
			// }

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private class ExecuteRouteRoad extends AsyncTask<Void, Void, Void> {
		Road roads;
		RoadManager roadmanager;

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			AddOverlayDefault();

			roadmanager = new luanvan.routing.MapQuestRoadManager();
			// RoadManager roadmanager=new luanvan.routing.OSRMRoadManager();
			// roadmanager.addRequestOption("route=bicycle");
			roadmanager.addRequestOption("routeType=bicycle");
			ArrayList<GeoPoint> wayspoints = new ArrayList<GeoPoint>();
			wayspoints.add(startPoint);
			wayspoints.add(destinationPoint);
			// wayspoints.add(new GeoPoint(10.767431,106.608406));
			roads = roadmanager.getRoad(wayspoints);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			if (roads.mNodes.size() <= 0) {
				Toast.makeText(getBaseContext(),
						"Không tìm thấy kết nối internet", Toast.LENGTH_LONG)
						.show();
				return;
			}

			if (listRoadNodes != null) {

				listRoadNodes.clear();
			}

			// luu cac vi tri de ve mui ten
			listRoadNodes = roadmanager.getListRoadNode();

			roadOverlay.clearPath();

			for (int i = 0; i < roads.mNodes.size(); i++) {
				RoadNode node = roads.mNodes.get(i);
				GeoPoint p = new GeoPoint(node.mLocation.getLatitudeE6(),
						node.mLocation.getLongitudeE6());
				roadOverlay.addPoint(p);
			}
			// Add Route Overlays into map
			map.getOverlays().add(roadOverlay);
			int count = 0;
			for (int i = 0; i < listRoadNodes.size() - 2; i+=2) {
				Overlay ns = new DrawableMapOverlay(getBaseContext(),
						listRoadNodes.get(i).mLocation,
						listRoadNodes.get(i + 1).mLocation);
				count++;
				if (count == 2) {
					map.getOverlays().add(ns);
					count = 0;
				}

			}
			// arrow_overlays.addAll(lstArrow);
			map.invalidate();

			TextView txinfo = (TextView) findViewById(R.id.routeInfo);
			// String km=roads.mLength
			txinfo.setText(String.valueOf("Dài : "
					+ String.format("%.2f", roads.mLength) + " km"));

			listInstruction = roadmanager.getInstruction();
			ShowInstruction();
		}

	}

	private class ExecuteRouteBus extends AsyncTask<Void, Void, Void> {
		ArrayList<PathBus> pathBus = new ArrayList<PathBus>();
		JSONObject jsonObject;
		JSONArray arrayPath = null;

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			dsPathBus.clear();

			// connection.doGet("http://bando24h.com/Server.aspx?action=FindRouteWithConstraint&FindRange=400&NearStationRange=200&WalkSpeed=5&BusSpeed=30&MaxChange=2&X1=684920.60&Y1=1192530.94&X2=680208.62&Y2=1191577.19");

			JSONParser jsonParser = new JSONParser();

			jsonObject = jsonParser.getJSONFromUrl(getURL());

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (jsonObject == null) {
				Toast.makeText(getBaseContext(),
						"Không tìm thấy kết nối internet", Toast.LENGTH_LONG)
						.show();
				return;
			}

			try {
				if (jsonObject.getBoolean(TAG_FOUND)) {
					arrayPath = jsonObject.getJSONArray(TAG_RESULT)
							.getJSONObject(0).getJSONArray(TAG_PATHS);
					for (int i = 0; i < arrayPath.length(); i++) {
						JSONObject obj = arrayPath.getJSONObject(i);
						PathBus bus = new PathBus();
						bus.KhoangCach = obj.getDouble(TAG_KHOANGCACH);
						bus.ThoiGian = obj.getDouble(TAG_THOIGIAN);
						bus.KMLRoute = obj.getString(TAG_KMLROUTE);
						JSONObject tuyen = obj.getJSONObject(TAG_TUYEN);
						bus.tuyen.MaTuyen = tuyen.getString(TAG_MATUYEN);
						bus.tuyen.TenTuyen = tuyen.getString(TAG_TENTUYEN);
						JSONObject tramdau = obj.getJSONObject(TAG_TRAMDAU);
						bus.tramDau.MaTram = tramdau.getString(TAG_MATRAM);
						bus.tramDau.TenTram = tramdau.getString(TAG_TENTRAM);
						GeoPoint p = utmlatlng.UTMRefToLatLng(
								tramdau.getDouble(TAG_X),
								tramdau.getDouble(TAG_Y));
						bus.tramDau.X = p.getLatitudeE6() / 1E6;
						bus.tramDau.Y = p.getLongitudeE6() / 1E6;
						JSONObject tramcuoi = obj.getJSONObject(TAG_TRAMCUOI);
						bus.tramCuoi.MaTram = tramcuoi.getString(TAG_MATRAM);
						bus.tramCuoi.TenTram = tramcuoi.getString(TAG_TENTRAM);
						bus.tramCuoi.X = tramcuoi.getDouble(TAG_X);
						bus.tramCuoi.Y = tramcuoi.getDouble(TAG_Y);

						pathBus.add(bus);
					}
				} else {
					Toast.makeText(getBaseContext(), "Không tìm thấy kết quả",
							Toast.LENGTH_LONG).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dsPathBus = pathBus;
			DrawPathBus();

		}

	}

	public ExtendedOverlayItem putMarkerItem(ExtendedOverlayItem item,
			GeoPoint p, int index, int titleResId, int markerResId,
			int iconResId) {
		if (item != null) {
			itineraryMarkers.removeItem(item);
		}
		Drawable marker = getResources().getDrawable(markerResId);
		String title = getResources().getString(titleResId);
		ExtendedOverlayItem overlayItem = new ExtendedOverlayItem(title, "", p,
				this);
		overlayItem.setMarkerHotspot(OverlayItem.HotspotPlace.BOTTOM_CENTER);
		overlayItem.setMarker(marker);
		if (iconResId != -1)
			overlayItem.setImage(getResources().getDrawable(iconResId));
		overlayItem.setRelatedObject(index);
		itineraryMarkers.addItem(overlayItem);
		map.invalidate();
		// Start geocoding task to update the description of the marker with its
		// address:

		return overlayItem;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		Toast.makeText(
				MainActivity.this,
				String.valueOf(location.getLatitude()) + "\n"
						+ String.valueOf(location.getLongitude()),
				Toast.LENGTH_LONG).show();
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	// ///////////////////// su kien map event overlay
	@Override
	public boolean singleTapUpHelper(IGeoPoint p) {
		// TODO Auto-generated method stub
		Log.d("tap", "tap");
		return false;
	}

	@Override
	public boolean longPressHelper(IGeoPoint p) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean doubleTapUpHelper(int zoomlevel) {
		// TODO Auto-generated method stub
		return false;
	}
}
